<template>
	<view class="wrap">
		<view class="header-content">
			<view class="left-salary-info">
				<text class="salary-amount">{{payrollData.actualSalary}}</text>
				<text class="salary-label">本月应发工资</text>
			</view>
			<view class="month-display">
				<text class="month-text">{{ payrollData.salaryDate }}</text>
			</view>
		</view>

		<view class="detail-card">
			<view class="detail-item">
				<text class="detail-value">{{payrollData.leaveDays}}</text>
				<text class="detail-label">请假天数</text>
			</view>
			<view class="detail-item">
				<text class="detail-value">{{payrollData.baseSalary}}</text>
				<text class="detail-label">基本工资</text>
			</view>
			<view class="detail-item">
				<text class="detail-value">{{payrollData.commission}}</text>
				<text class="detail-label">销量提成</text>
			</view>
		</view>

		<u-cell-group title="基本信息">
			<u-cell-item :arrow="false" title="员工姓名" class="required">
				<u-input disabled v-model="payrollData.createByName" placeholder="请输入员工姓名" :border="false" :custom-style="{ textAlign: 'right' }" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="店铺名称" class="required">
				<u-input disabled v-model="payrollData.officeName" placeholder="请输入店铺名称" :border="false" :custom-style="{ textAlign: 'right' }" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="基本工资" class="required" style="display: none;">
				<u-input disabled v-model="payrollData.baseSalary" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('baseSalary')" />
			</u-cell-item>
		</u-cell-group>

		<u-cell-group title="奖金说明">
			<u-cell-item :arrow="false" title="销量提成" style="display: none;">
				<u-input disabled v-model="payrollData.commission" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('commission')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="超额奖励">
				<u-input disabled v-model="payrollData.excessReward" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('excessReward')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="任务奖励">
				<u-input disabled v-model="payrollData.taskReward" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('taskReward')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="超勤奖励">
				<u-input disabled v-model="payrollData.fullAttendanceReward" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('fullAttendanceReward')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="房补费用">
				<u-input disabled v-model="payrollData.housingSubsidyFee" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('housingSubsidyFee')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="出票奖励">
				<u-input disabled v-model="payrollData.ticketIssuanceReward" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('ticketIssuanceReward')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="分红费用">
				<u-input disabled v-model="payrollData.dividendSetting" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('dividendSetting')" />
			</u-cell-item>
		</u-cell-group>

		<u-cell-group title="支出说明">
			<!-- <u-cell-item :arrow="false" title="考勤罚款">
				<u-input disabled v-model="payrollData.attendanceFines" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('attendanceFines')" />
			</u-cell-item> -->
			<u-cell-item :arrow="false" title="违规罚款">
				<u-input disabled v-model="payrollData.violationFines" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('violationFines')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="宿舍费用">
				<u-input disabled v-model="payrollData.dormitoryFees" placeholder="0.00" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('dormitoryFees')" />
			</u-cell-item>
			<u-cell-item :arrow="false" title="其他费用">
				<u-input disabled v-model="payrollData.otherExpenses" placeholder="请输入其他费用" :border="false" type="number" :custom-style="{ textAlign: 'right' }" @blur="formatNumberOnBlur('otherExpenses')" />
			</u-cell-item>
		</u-cell-group>

		<u-cell-group title="实发工资" style="display: none;">
			<u-cell-item :arrow="false" title="实发工资">
				<u-input disabled v-model="payrollData.actualSalary"  :border="false" type="number" :custom-style="{ textAlign: 'right' }"  />
			</u-cell-item>
		</u-cell-group>

		<u-cell-group title="计算公式" style="display: none;">
			<u-cell-item :arrow="false" title="">
				<u-input 
					disabled
					v-model="payrollData.calculationFormula" 
					placeholder="请输入计算公式" 
					:border="false" 
					type="text"
					:custom-style="{ textAlign: 'left' }" 
				/>
			</u-cell-item>
		</u-cell-group>

		<view class="form-footer">
			<u-button class="btn" type="primary" @click="close()">关闭</u-button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			payrollData: {
				id:'',
				salaryDateShow:'',
				salaryDate: '2025-05',
				createByName: '张晓燕',
				officeName: '大柳树',
				baseSalary: '3000.00',
				commission: '9401.97',
				excessReward: '2200.99',
				taskReward: '1000.00',
				fullAttendanceReward: '400.00',
				housingSubsidyFee: '0.00',
				ticketIssuanceReward: '1208.00',
				dividendSetting: '0.00',
				attendanceFines: '0.00',
				violationFines: '0.00',
				dormitoryFees: '0.00',
				otherExpenses: '',
				calculationFormula: 'A+T*C+(T-B)*D+E+F+G+(X*H)+I+(N*J)+K+L+M',
				actualSalary: '0.00',
				totalQuantity:  '0.00',
				bfdTotalQuantity: '0.00',
				leaveDays: '0',
				restPriceDifference:'0.00',
			}
		};
	},
	onLoad(params) {
		// 设置页面标题
		let title = '工资条'
		uni.setNavigationBarTitle({
			title: title
		});
		
		// 设置导航栏颜色
		uni.setNavigationBarColor({
			frontColor: '#ffffff', // 前景颜色，如标题和返回按钮颜色，只能是 #ffffff 或 #000000
			backgroundColor: '#FF9B00', // 背景颜色
			animation: { // 动画效果
				duration: 300,
				timingFunc: 'easeOut'
			}
		});
		
		// 从全局存储中获取数据，避免URL编码问题
		let itemDetail = uni.getStorageSync('payrollDetailData');
		// 清除存储的数据
		uni.removeStorageSync('payrollDetailData');
		// 回显数据到表单
		this.payrollData = {
			id: itemDetail.id || '',
			salaryDateShow: itemDetail.salaryDateShow || '',
			salaryDate: itemDetail.salaryDate || '2025-05',
			createByName: itemDetail.createByName || '',
			officeName: itemDetail.officeName || '',
			baseSalary: itemDetail.baseSalary || '0.00',
			commission: itemDetail.commission || '0.00',
			excessReward: itemDetail.excessReward || '0.00',
			taskReward: itemDetail.taskReward || '0.00',
			fullAttendanceReward: itemDetail.fullAttendanceReward || '0.00',
			housingSubsidyFee: itemDetail.housingSubsidyFee || '0.00',
			ticketIssuanceReward: itemDetail.ticketIssuanceReward || '0.00',
			dividendSetting: itemDetail.dividendSetting || '0.00',
			attendanceFines: itemDetail.attendanceFines || '0.00',
			violationFines: itemDetail.violationFines || '0.00',
			dormitoryFees: itemDetail.dormitoryFees || '0.00',
			otherExpenses: itemDetail.otherExpenses || '0.00',
			calculationFormula: itemDetail.calculationFormula || 'A+T*C+(T-B)*D+E+F+G+(X*H)+I+(N*J)+K+L+M',
			actualSalary: itemDetail.actualSalary || '0.00',
			totalQuantity: itemDetail.totalQuantity || '0.00',
			bfdTotalQuantity: itemDetail.bfdTotalQuantity || '0.00',
			leaveDays: itemDetail.leaveDays || '0',
			restPriceDifference: itemDetail.restPriceDifference || '0.00',
		}
	},
	computed: {
		calculatedNetSalary() {
			// 使用公式计算实发工资
			const result = this.calculateByFormula();
			return result.toFixed(2);
		}
	},
	methods: {
		// 格式化数字输入
		formatNumber(value) {
			if (!value) return '0.00';
			const num = parseFloat(value);
			return isNaN(num) ? '0.00' : num.toFixed(2);
		},
		
		// 验证数据
		validateData() {
			const requiredFields = ['createByName', 'officeName', 'baseSalary'];
			for (const field of requiredFields) {
				if (!this.payrollData[field]) {
					uni.showToast({
						title: `请填写${this.getFieldLabel(field)}`,
						icon: 'none'
					});
					return false;
				}
			}
			
			// 验证数字字段
			const numericFields = [
				'baseSalary', 'commission', 'excessReward', 'taskReward',
				'fullAttendanceReward', 'housingSubsidyFee', 'ticketIssuanceReward', 'dividendSetting',
				'attendanceFines', 'violationFines', 'dormitoryFees', 'otherExpenses',
			];
			
			for (const field of numericFields) {
				const value = this.payrollData[field];
				if (value && (isNaN(value) || parseFloat(value) < 0)) {
					uni.showToast({
						title: `${this.getFieldLabel(field)}必须是有效的正数`,
						icon: 'none'
					});
					return false;
				}
			}
			
			return true;
		},
		
		// 获取字段标签
		getFieldLabel(field) {
			const labels = {
				createByName: '员工姓名',
				officeName: '店铺名称',
				baseSalary: '基本工资',
				commission: '销量提成',
				excessReward: '超额奖励',
				taskReward: '任务奖励',
				fullAttendanceReward: '超勤奖励',
				housingSubsidyFee: '房补费用',
				ticketIssuanceReward: '出票奖励',
				dividendSetting: '分红费用',
				attendanceFines: '考勤罚款',
				violationFines: '违规罚款',
				dormitoryFees: '宿舍费用',
				otherExpenses: '其他费用',
			};
			return labels[field] || field;
		},
		
		// 保存数据
		async save() {
			if (!this.validateData()) {
				return;
			}
			
			// 使用公式计算结果更新实发工资
			this.payrollData.actualSalary = this.calculateByFormula().toFixed(2);
			
			try {
				// 这里添加交款逻辑
				uni.showModal({
					title: '保存工资',
					content: `确定要保存吗？`,
					success: (res) => {
						if (res.confirm) {
							this.$u.api.payroll.save(this.payrollData).then(res => {
								if (res.result === 'true') {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
									
									// 保存成功后可以返回上一页或刷新数据
									setTimeout(() => {
										uni.navigateBack();
									}, 1500);
								} else {
									uni.showToast({
										title: res.message || '保存失败',
										icon: 'none'
									});
								}
							}).catch(err => {
								uni.showToast({
									title: '生成失败，请重试',
									icon: 'none'
								});
							});
						}
					}
				});
				
			} catch (error) {
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'none'
				});
			}
		},
		
		// 关闭页面
		close() {
			uni.navigateBack();
		},
		
		// 失去焦点时格式化数字
		formatNumberOnBlur(field) {
			const value = this.payrollData[field];
			if (value && !isNaN(value)) {
				this.payrollData[field] = parseFloat(value).toFixed(2);
			}
		},
		
		// 解析并计算公式
		calculateByFormula() {
			const formula = this.payrollData.calculationFormula || 'A+T*C+(T-B)*D+E+F+G+(X*H)+I+(N*J)+K+L+M';
			
			// 严格按照公式中的变量映射，不做任何曲解
			const variables = {
				'A': parseFloat(this.payrollData.baseSalary) || 0,           // 基本工资
				'B': parseFloat(this.payrollData.commission) || 0,           // 销量提成
				'C': parseFloat(this.payrollData.excessReward) || 0,         // 超额奖励
				'D': parseFloat(this.payrollData.taskReward) || 0,           // 任务奖励
				'E': parseFloat(this.payrollData.fullAttendanceReward) || 0, // 超勤奖励
				'F': parseFloat(this.payrollData.housingSubsidyFee) || 0,       // 房补费用
				'G': parseFloat(this.payrollData.ticketIssuanceReward) || 0,          // 出票奖励
				'H': parseFloat(this.payrollData.dividendSetting) || 0,      // 分红费用
				'I': parseFloat(this.payrollData.attendanceFines) || 0,       // 考勤罚款
				'J': parseFloat(this.payrollData.violationFines) || 0,        // 违规罚款
				'K': parseFloat(this.payrollData.dormitoryFees) || 0,     // 宿舍费用
				'L': parseFloat(this.payrollData.otherExpenses) || 0,        // 其他费用
				'M': parseFloat(this.payrollData.restPriceDifference) || 0,                                                      // 预留变量
				'N': parseFloat(this.payrollData.restPriceDifference) || 0,                                                      // 系数变量
				'T': parseFloat(this.payrollData.totalQuantity) || 0,          // 销量提成（同B）
				'X': parseFloat(this.payrollData.bfdTotalQuantity) || 0,                                                       // 系数变量
			};
			
			try {
				// 替换公式中的变量
				let expression = formula;
				for (const [key, value] of Object.entries(variables)) {
					expression = expression.replace(new RegExp(key, 'g'), value);
				}
				
				// 调试信息
				console.log('原始公式:', formula);
				console.log('变量映射:', variables);
				console.log('替换后表达式:', expression);
				
				// 安全地计算表达式
				const result = this.safeEval(expression);
				console.log('计算结果:', result);
				return isNaN(result) ? 0 : result;
			} catch (error) {
				console.error('公式计算错误:', error);
				return 0;
			}
		},
		
		// 安全的表达式计算
		safeEval(expression) {
			// 只允许数字、运算符和括号
			if (!/^[0-9+\-*/().\s]+$/.test(expression)) {
				throw new Error('表达式包含非法字符');
			}
			
			// 使用 Function 构造函数安全计算
			return new Function('return ' + expression)();
		},
	},
	
	watch: {
		// 监听公式字段，确保数据正确
		'payrollData.calculationFormula'(newVal) {
			// 现在不需要特殊处理，因为数据传递已经优化
		},
	},
};
</script>

<style lang="scss">
	.wrap {
		padding: 0;
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 200rpx; /* 为固定按钮留出空间 */
		padding-top: 370rpx; /* 为固定的头部内容留出空间 */
	}

	.header-content {
		background-color: #FF9B00; /* 橙色背景 */
		padding: 40rpx 30rpx 120rpx; /* 留出空间给下面的卡片重叠 */
		color: #ffffff;
		position: fixed; /* 固定定位 */
		top: 80rpx; /* 固定在顶部 */
		left: 0;
		right: 0;
		z-index: 10; /* 确保在最上层 */
		display: flex; /* 使用Flexbox布局 */
		justify-content: space-between; /* 左右两端对齐 */
		align-items: center; /* 垂直居中 */
	}

	/* app环境下顶部距离为0 */
	/* #ifdef APP-PLUS */
	.header-content {
		top: 0;
	}
	/* #endif */

	.left-salary-info {
		text-align: left; /* 左对齐 */
		margin-bottom: 0; /* 移除之前的底部外边距 */
	}

	.salary-amount {
		font-size: 80rpx;
		font-weight: bold;
		display: block;
		text-align: left; /* 左对齐 */
	}

	.salary-label {
		font-size: 28rpx;
		opacity: 0.8;
		display: block;
		margin-top: 10rpx;
		text-align: left; /* 左对齐 */
	}

	.month-display {
		background-color: rgba(0, 0, 0, 0.3); /* 深色半透明背景 */
		color: #ffffff;
		border-radius: 30rpx;
		padding: 10rpx 20rpx;
		font-size: 26rpx;
		display: inline-flex;
		align-items: center;
	}

	.month-text {
		font-size: 28rpx;
		font-weight: normal;
		display: inline-block;
		margin-right: 10rpx; /* 文字与图标的间距 */
	}

	.detail-card {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 30rpx; /* 移除负边距，因为现在是固定定位 */
		padding: 30rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		position: fixed; /* 固定定位 */
		top: 330rpx; /* 位于header-content下方 */
		left: 0;
		right: 0;
		z-index: 99; /* 确保在header-content下方但在其他内容上方 */
	}
	/* app环境下顶部距离为0 */
	/* #ifdef APP-PLUS */
	.detail-card {
		top: 250rpx;
	}
	/* #endif */
	.detail-item {
		text-align: center;
		flex: 1;
	}

	.detail-value {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
	}

	.detail-label {
		font-size: 24rpx;
		color: #999;
		display: block;
		margin-top: 5rpx;
	}

	.u-cell-group {
		margin: 20rpx 30rpx;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.u-cell-group__title {
		font-weight: bold;
		font-size: 32rpx;
		color: #333;
		padding: 20rpx 30rpx;
		background-color: #f8f9fa;
		border-bottom: 1rpx solid #e9ecef;
	}
	/deep/ .u-cell-item-box{
		margin: 0 30rpx;
		border-radius: 30rpx;
	}
	.u-cell-item {
		background-color: #fff;
		border-radius: 12rpx;
	}

	.u-cell-item__title {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.u-input {
		text-align: right;
		font-size: 28rpx;
		color: #666;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 5rpx 20rpx;
	}

	.u-input__input {
		text-align: right !important;
	}

	// 确保输入框内容右对齐
	.u-cell-item .u-input {
		text-align: right !important;
	}

	.u-cell-item .u-input__input {
		text-align: right !important;
	}

	// 输入框占位符样式
	.u-input__input::placeholder {
		text-align: right !important;
		color: #c0c4cc;
	}

	// 输入框聚焦时的样式
	.u-input__input:focus {
		text-align: right !important;
	}

	// 数字输入框特殊样式
	.u-input[type="number"] .u-input__input {
		color: #409eff;
		font-weight: 500;
		text-align: right !important;
	}

	.form-footer {
		width: 100%;
		position: fixed;
		bottom: -20rpx;
		left: -10rpx;
		right: 0;
		display: flex;
		justify-content: space-between;
		// padding: 20rpx 30rpx;
		background-color: #fff;
		// border-top: 1rpx solid #e9ecef;
		// box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
		// gap: 20rpx;
		z-index: 999;
	}

	.btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: 500;
	}

	// 必填字段标识
	.u-cell-item__title::before {
		content: '*';
		color: #f56c6c;
		margin-right: 4rpx;
	}

	// 非必填字段不显示星号
	.u-cell-item:not(.required) .u-cell-item__title::before {
		display: none;
	}

	// 公式输入框特殊样式
	.u-cell-group:last-of-type .u-cell-item .u-input {
		text-align: left !important;
		min-height: 80rpx;
		padding: 20rpx;
	}

	.u-cell-group:last-of-type .u-cell-item .u-input__input {
		text-align: left !important;
		font-family: 'Courier New', monospace;
		font-size: 26rpx;
		line-height: 1.5;
		word-break: break-all;
		white-space: pre-wrap;
	}
</style> 